import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/info_row_widget.dart';
import 'package:bike_ride/common/widget/page_title_widget.dart';
import 'package:bike_ride/common/widget/xb_button.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/model/pay/view/pay_box_v.dart';
import 'package:bike_ride/model/pay/view_model/pay_vm.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/theme_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

///结束行程-支付页
class PayView extends BaseStatefulPage<PayViewModel> {
  final Map<String,dynamic> arguments;
  const PayView({required this.arguments,super.key});

  @override
  PayViewState createState() => PayViewState();
}

class PayViewState
    extends BaseStatefulPageState<PayView, PayViewModel> {
  final tapStandardGestureRecognizer = TapGestureRecognizer();
  final tapServiceGestureRecognizer = TapGestureRecognizer();
  final padding = EdgeInsets.symmetric(vertical: 12.rpx);


  @override
  void initAttribute() {

  }

  @override
  void initObserver() {}

  void notifyChange() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  PayViewModel viewBindingViewModel() {
    return PayViewModel()..viewState = this;
  }

  @override
  void dispose() {
    tapStandardGestureRecognizer.dispose();
    tapServiceGestureRecognizer.dispose();
    super.dispose();
  }

  @override
  Widget appBuild(BuildContext context) {
    return Scaffold(
        backgroundColor: ColorStyles.color_F3F4F5,
        extendBodyBehindAppBar: true,
        body: Column(
          children: [
            PageTitleWidget(title: S.current.tripEnd,),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: ThemeStyles.pagePaddingHorizontal),
              child: Column(
                children: [
                  _buildTop(),
                  _buildContainer1(),
                  viewModel!.payedOrderDetailM == null?
                  _buildContainer2():_buildContainer3(),

                  SizedBox(height: 16.rpx,),
                  RichText(text: TextSpan(
                    style: TextStyle(color: ColorStyles.color_333333,fontSize: 24.rpx),
                    children: [
                      TextSpan(
                        text: S.current.doubtInRiding,
                      ),
                      TextSpan(
                          text: S.current.chargeStandard,
                          style: TextStyle(color: Theme.of(context).colorScheme.primary,fontSize: 24.rpx),
                          recognizer: tapStandardGestureRecognizer
                            ..onTap = () {
                              NavigatorUtil.push(context, Routers.freightView);
                            }
                      ),
                      TextSpan(
                        text: S.current.or,
                      ),
                      TextSpan(
                          text: S.current.needService,
                          style: TextStyle(color: Theme.of(context).colorScheme.primary,fontSize: 24.rpx),
                          recognizer: tapServiceGestureRecognizer..onTap =(){
                            NavigatorUtil.push(context, Routers.questionView);
                          }
                      ),
                    ],
                  )),
                  SizedBox(height: 32.rpx,),

                  if(viewModel!.payedOrderDetailM?.orderStatus == null || viewModel!.payedOrderDetailM?.orderStatus == 2)
                    XbButton(
                      isDefault: false,
                      width: MediaQuery.of(context).size.width,
                      child: Text(S.current.payNow),
                      onPressed: ()async{
                        //再次请求，避免网络请求失败
                        if(viewModel!.unPayInfoM == null){
                          viewModel!.getUnPayInfo(viewModel!.orderId);
                        }else if(viewModel!.discountStatM == null){
                          viewModel!.getFinanceInfo();
                        }else{
                          await showCupertinoModalPopup(
                            context: context,
                            builder: (context) => PayBoxView(arguments: {
                              'order_id': viewModel!.orderId,
                              'finance_info': viewModel!.discountStatM,
                              'un_pay': viewModel!.unPayInfoM,
                            }),
                          );
                          viewModel!.getUnPayInfo(viewModel!.orderId);
                        }
                      },
                    )
                ],
              ),
            )
          ],
        ));
  }

  //1进行中 2为待支付 3为已支付  4为部分退款 5为已退款
  final miniPayStatusMap = {
    1: S.current.riding,
    2: S.current.endReturnSuccess,//待支付
    3: S.current.paySuccess,
    4: S.current.partialRefunded,//部分退款
    5: S.current.refunded,
  };

  Widget _buildTop(){
    return Row(
      children: [
        //[miniPayStatusMap] 1、2
        Image.asset([null,1,2].contains(viewModel!.payedOrderDetailM?.orderStatus)?'assets/applet/pay_return_icon.png':'assets/common_v2/success.png',width: 80.rpx,height:80.rpx,),
        SizedBox(width: 12.rpx,),
        Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(miniPayStatusMap[viewModel!.payedOrderDetailM?.orderStatus??2]??'-',style: TextStyle(color: ColorStyles.color_333333,fontSize: 36.rpx,fontWeight: FontWeight.bold),),
            GestureDetector(
              onTap: (){
                EasyLoading.showError(S.current.developerTips);
                // NavigatorUtil.push(context, Routers.orderDetailView,arguments: {"order_id":viewModel!.orderId});
              },
              child: Row(
                children: [
                  // Text('查看行程详情',style: TextStyle(color: Theme.of(context).colorScheme.primary,fontSize: 24.rpx),),
                  // Icon(Icons.keyboard_arrow_right_rounded,size: 32.rpx,color: Theme.of(context).colorScheme.primary,)
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildContainer1(){
    return Container(
      margin: EdgeInsets.symmetric(vertical: 12.rpx),
      padding: EdgeInsets.symmetric(horizontal: 16.rpx,vertical: 8.rpx),
      decoration: BoxDecoration(
        color: ColorStyles.color_FFFFFF,
        borderRadius: BorderRadius.circular(20.rpx),
      ),
      child: Column(
        children: [
          InfoRowWidget(
            left: S.current.startPrice,
            padding: padding,
            right: '${viewModel?.unPayInfoM?.properties?.payByStart??0}${S.current.yuan}',
          ),
          InfoRowWidget(
            left: S.current.timeFee,
            padding: padding,
            right: '${viewModel?.unPayInfoM?.exceedPrice??0}${S.current.yuan}',
          ),
          InfoRowWidget(
            left: S.current.violationFee,
            padding: padding,
            right: '${viewModel?.unPayInfoM?.properties?.trafficFare??0}${S.current.yuan}',
          ),
          Container(
            decoration: BoxDecoration(
              color: const Color(0xFFF8FaFF),
              borderRadius: BorderRadius.all(Radius.circular(6.rpx))
            ),
            child: Builder(builder: (context){
              final trafficFares = viewModel?.unPayInfoM?.properties?.trafficFare??0;
              final serviceOutwardFees = viewModel?.unPayInfoM?.properties?.serviceOutwardFee??0;
              final noStopOutwardFees = viewModel?.unPayInfoM?.properties?.nostopOutwardFee??0;
              final helmetFees = viewModel?.unPayInfoM?.properties?.helmetFee??0;
              final standardParkingFees = viewModel?.unPayInfoM?.properties?.standardParkingFee??0;

              final List<Widget> items = [
                if(trafficFares>0)
                  _buildViolationItem(trafficFares,'${S.current.serviceFee}\n${S.current.outwardParkArea}'),
                if(serviceOutwardFees>0)
                  _buildViolationItem(serviceOutwardFees,'${S.current.serviceFee}\n${S.current.outwardOperationArea}'),
                if(noStopOutwardFees>0)
                  _buildViolationItem(noStopOutwardFees,S.current.noStopServiceFee),
                if(helmetFees>0)
                  _buildViolationItem(helmetFees,S.current.helmetManageFee),
                if(standardParkingFees>0)
                  _buildViolationItem(standardParkingFees,S.current.irregularParkingFees),
              ];

              if(items.isEmpty){
                return const SizedBox();
              }
              return Padding(
                padding: EdgeInsets.symmetric(vertical: 4.rpx),
                child: Row(
                  children: items
                      .map((e) => Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              _buildUnit(e == items.first),
                              e,
                            ],
                          ))
                      .toList(),
                ),
              );
              },),
          ),
          if((viewModel?.unPayInfoM?.properties?.studyFreeTrafficReduction??0)>0)
            InfoRowWidget(
              left: S.current.learnToDispatchingFees,
              padding: padding,
              right: '${viewModel?.unPayInfoM?.properties?.studyFreeTrafficReduction??0}${S.current.yuan}',
            ),
          if((viewModel?.unPayInfoM?.properties?.ftRidingFeeReduction??0)>0)
            InfoRowWidget(
              left: S.current.firstRideFeeWaived,
              padding: padding,
              right: '${viewModel?.unPayInfoM?.properties?.ftRidingFeeReduction??0}${S.current.yuan}',
            ),
          if((viewModel?.unPayInfoM?.properties?.ftTrafficFareReduction??0) >0)
            InfoRowWidget(
              left: S.current.firstDispatchFeeWaived,
              padding: padding,
              right: '${viewModel?.unPayInfoM?.properties?.ftTrafficFareReduction??0}${S.current.yuan}',
            ),
          if((viewModel?.unPayInfoM?.properties?.numberReduction??0)>0)
            InfoRowWidget(
              left: S.current.discountActivity,
              padding: padding,
              right: '${viewModel?.unPayInfoM?.properties?.numberReduction??0}${S.current.yuan}',
            ),
        ],
      ),

    );
  }


  Widget _buildContainer2(){
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.rpx,vertical: 8.rpx),
      decoration: BoxDecoration(
        color: ColorStyles.color_FFFFFF,
        borderRadius: BorderRadius.circular(20.rpx),
      ),
      child: Column(
        children: [
          if((viewModel?.unPayInfoM?.costPrice??0)>0)
          InfoRowWidget(
            left: S.current.orderAmount,
            right: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('${viewModel?.unPayInfoM?.costPrice??0}',style: TextStyle(fontSize: 56.rpx,fontWeight: FontWeight.w700,color: Theme.of(context).colorScheme.primary),),
                Text(S.current.yuan,style: TextStyle(fontSize: 28.rpx,color: ColorStyles.color_333333),)
              ],
            ),
            padding: padding,
          ),
          if((viewModel?.unPayInfoM?.prePayAmount??0)>0)
            InfoRowWidget(
              left: S.current.prepayAmount,
              leftColor: const Color(0xffee6f2d),
              padding: padding,
              right: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('-${viewModel?.unPayInfoM?.prePayAmount??0}',style: TextStyle(fontSize: 56.rpx,fontWeight: FontWeight.w700,color: const Color(0xffee6f2d),)),
                  Text(S.current.yuan,style: TextStyle(fontSize: 28.rpx,color: ColorStyles.color_333333),)
                ],
              ),
            ),
          if((viewModel?.unPayInfoM?.giveBalance??0)>0)
            InfoRowWidget(
              left: S.current.giveBalancePrice,
              leftColor: const Color(0xffee6f2d),
              padding: padding,
              right: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('-${viewModel?.unPayInfoM?.giveBalance??0}',style: TextStyle(fontSize: 56.rpx,fontWeight: FontWeight.w700,color: const Color(0xffee6f2d),)),
                  Text(S.current.yuan,style: TextStyle(fontSize: 28.rpx,color: ColorStyles.color_333333),)
                ],
              ),
            ),
          if((viewModel?.unPayInfoM?.orderType??0) == 4 && ((viewModel?.unPayInfoM?.amount??0)>=0))
            InfoRowWidget(
              left: S.current.payableAmount,
              leftColor: const Color(0xffee6f2d),
              padding: padding,
              right: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('${viewModel?.unPayInfoM?.amount??0}',style: TextStyle(fontSize: 56.rpx,fontWeight: FontWeight.w700,color: const Color(0xffee6f2d),)),
                  Text(S.current.yuan,style: TextStyle(fontSize: 28.rpx,color: ColorStyles.color_333333),)
                ],
              ),
            ),
        ],
      ),

    );
  }


  Widget _buildContainer3(){
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.rpx,vertical: 8.rpx),
        decoration: BoxDecoration(
          color: ColorStyles.color_FFFFFF,
          borderRadius: BorderRadius.circular(20.rpx),
        ),
      child: Column(
        children: [
          InfoRowWidget(
            left: S.current.orderId,
            padding: padding,
            right: '${viewModel?.payedOrderDetailM?.orderid}',
          ),
          InfoRowWidget(
            left: S.current.vehicleNumber,
            padding: padding,
            right: '${viewModel?.payedOrderDetailM?.vid}',
          ),
          // if((viewModel?.payedOrderDetailM?.costprice??0) >0)
            InfoRowWidget(
              left: S.current.totalFee,
              padding: padding,
              right: '${viewModel?.payedOrderDetailM?.costprice??0}${S.current.yuan}',
            ),
          if((viewModel?.payedOrderDetailM?.givebalance??0) >0)
            InfoRowWidget(
              left: S.current.giveBalancePrice,
              padding: padding,
              leftColor: const Color(0xffee6f2d),
              rightColor: const Color(0xffee6f2d),
              right: '${viewModel?.payedOrderDetailM?.givebalance??0}${S.current.yuan}',
            ),
          // if((viewModel?.payedOrderDetailM?.balanceAmount??0) >0)
            InfoRowWidget(
              left: S.current.realAmount,
              padding: padding,
              right: '${(viewModel?.payedOrderDetailM?.balanceAmount??0) + (viewModel?.payedOrderDetailM?.payAmount??0)}${S.current.yuan}',
            ),
          InfoRowWidget(
            left: S.current.payType,
            padding: padding,
            right: (viewModel?.payedOrderDetailM?.paytype == 11)?S.current.payOverseas:S.current.payBalance,
          ),
        ]
      )
    );
  }

  Widget _buildUnit(bool isFirst) {
    return Padding(padding: EdgeInsets.symmetric(horizontal: 8.rpx),
      child: Text(isFirst ? '=' : '+',
        style: TextStyle(color: ColorStyles.color_333333, fontSize: 18.rpx),),);
  }

  Widget _buildViolationItem(num money,String content){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('¥$money',style: TextStyle(color: ColorStyles.color_333333,fontSize: 18.rpx),),
        Text(content,style: TextStyle(color: ColorStyles.color_999999,fontSize: 18.rpx),textAlign: TextAlign.center,),
      ],
    );
  }
}



